import cv2
from cvzone.HandTrackingModule import HandDetector
import cvzone

cap = cv2.VideoCapture(0)
cap.set(3,1280)
cap.set(4,720)
detector = HandDetector(detectionCon=0.8)
# 保存
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
fourcc = cv2.VideoWriter_fourcc(*'XVID')
vm = cv2.VideoWriter('fy.avi', fourcc, 20.0, (frame_width, frame_height))

class DrawRect():
    def __init__(self,center,size=[200,200],colorR=(255,0,255)):
        self.center = center
        self.size = size
        self.colorR = colorR

    def update_draw(self,course):
        cx,cy = self.center
        w,h = self.size
        if cx - w // 2 < course[0] < cx + w // 2 and cy - h // 2 < course[1] < cy + h // 2:
            self.center = course[:2]
            self.colorR = (0,255,0)
        else:
            self.colorR = (255,0,255)

# 显示框框3个
rectlist = []
for x in range(3):
    rectlist.append(DrawRect([x*250+100,100]))

while True:
    ret,frame = cap.read()
    hands,frame = detector.findHands(frame)
    if hands:
        hand1 = hands[0]
        # 获取手的所有地标
        lmlist = hand1["lmList"]
        # center = hand1["center"]
        if lmlist:
            # 获取食指与中指距离
            l,_,_ = detector.findDistance(lmlist[8][:2],lmlist[12][:2],frame)
            # 获取食指的地标
            course = lmlist[8]
            if l < 45:
                for rect in rectlist:
                    rect.update_draw(course)
    # 增加3个框框
    for rect in rectlist:
        cx, cy = rect.center
        w, h = rect.size
        cvzone.cornerRect(frame,(cx-w//2,cy-h//2,w,h))
        cv2.rectangle(frame,(cx-w//2,cy-h//2),(cx+w//2,cy+h//2),rect.colorR,cv2.FILLED)
    vm.write(frame)
    cv2.imshow("Image",frame)
    cv2.waitKey(1)
